package com.boarsoft.boar.sys;

import java.text.MessageFormat;
import java.util.Date;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.common.SMSUtil;
import com.boarsoft.boar.common.ValidateUtil;
import com.boarsoft.boar.sys.entity.SysSms;
import com.boarsoft.boar.sys.entity.SysUser;
import com.boarsoft.boar.sys.entity.SysVerify;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.RandomUtil;

@Component("sysMessager")
public class SysMessager {
	protected Log log = LogFactory.getLog(this.getClass());
	@Autowired
	protected Mailer mailer;
	@Autowired
	protected SysUserBiz sysUserBiz;
	@Autowired
	protected SysSmsBiz sysSmsBiz;
	@Autowired
	protected SysVerifyBiz sysVerifyBiz;

	/**
	 * 发送站内消息
	 * 
	 * @param sms
	 */
	public void sendMessage(SysSms sms) {
		String from = sms.getFrom();
		if (Util.strIsEmpty(from)) {
			from = "系统消息";
		} else {
			SysUser u = sysUserBiz.get(from);
			String email = u.getEmail();
			from = u.getName().concat("(").concat(Util.strIsNotEmpty(email) ? email : u.getPhone()).concat(")");
		}
		sms.setFrom(from);
		sms.setSendTime(Util.date2str(new Date(), Util.STDDTF));
		sysSmsBiz.save(sms);
	}
	
	public SysVerify makeAndSend(String code) {
		// 检查是否60秒内已发送过验证码
		SysVerify v = sysVerifyBiz.find(code);
		if (v != null) {
			return null;
		}
		// 生成验证码
		String vc = RandomUtil.genAz09(6);
		// String url = String.format("%s/sys/verify/check.do?u=%s&v=%s",
		// Config.HLY_WWW_URL, code, vc);
		// 创建一条验证记录，默认有效期是60秒
		v = new SysVerify();
		v.setCode(vc);
		// 发送验证短信或邮件
		ResourceBundle rb = ResourceBundle.getBundle("i18n/msg");
		if (ValidateUtil.isValidEmail(code)) {
			// 如果有登记邮箱
			v.setEmail(code);
			// 发送验证邮件
			String txt = rb.getString("email.verify.body");
			// txt = MessageFormat.format(txt, url);
			txt = MessageFormat.format(txt, vc);
			txt.concat(rb.getString("email.signature"));
			mailer.sendSimpleMail(code, null,
					rb.getString("email.verify.title"), txt);
		} else if (ValidateUtil.isValidPhone(code)) {
			// 如果有登记手机
			v.setPhone(code);
			// 发送验证短信
			SMSUtil.sendNow(code, "sms.verify", vc);
		} else {
			return null;
		}
		return v;
	}
}
